package aws.handler;

import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.axis.types.PositiveInteger;

import aws.*;
import edu.cuhk.cs.bookstore.model.Book;
import edu.cuhk.cs.bookstore.util.StringUtil;

public class ItemSearchRequestHandler extends AbstractRequestHandler {

	public ItemSearchRequestHandler() {
		super();
	}

	/*
	 * Only Return 10 Book
	 */
	public List<Book> searchByTitle(String name) {
		List<Book> books = new ArrayList<Book>();
		try {
			AWSECommerceServicePortType service = getWebService();
			Map<String, String> param = new HashMap<String, String>();
			param.put("TITLE", name);
			ItemSearch submit = createItemSearchParameter(param);
			ItemSearchResponse response = service.itemSearch(submit);
			if (response != null) {
				if (response.getItems() != null	&& response.getItems().length > 0) {
					Items items = response.getItems()[0];
					System.out.println("result size: " + items.getItem().length);
					for (int i = 0; i < items.getItem().length; i++) {
						Item item = items.getItem()[i];
						/***
						 *  Refer: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CHAP_response_elements.html
						 */
						Book book = new Book(
								item.getItemAttributes().getTitle(), 
								StringUtil.join(item.getItemAttributes().getAuthor(),","), 
								item.getItemAttributes().getISBN(), 
								item.getItemAttributes().getPublisher(), 
								StringUtil.parseDateFormat(item.getItemAttributes().getPublicationDate()));
						books.add(book);
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		return books;

	}
	
	/*
	 * Only Return 10 Book
	 */
	public List<Book> searchByName(String name) {
		List<Book> books = new ArrayList<Book>();
		try {
			AWSECommerceServicePortType service = getWebService();
			Map<String, String> param = new HashMap<String, String>();
			param.put("KEYWORDS", name);
			ItemSearch submit = createItemSearchParameter(param);
			ItemSearchResponse response = service.itemSearch(submit);
			if (response != null) {
				if (response.getItems() != null	&& response.getItems().length > 0) {
					Items items = response.getItems()[0];
					System.out.println("result size: " + items.getItem().length);
					for (int i = 0; i < items.getItem().length; i++) {
						Item item = items.getItem()[i];
						/***
						 *  Refer: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CHAP_response_elements.html
						 */
						Book book = new Book(
								item.getItemAttributes().getTitle(), 
								StringUtil.join(item.getItemAttributes().getAuthor(),","), 
								item.getItemAttributes().getISBN(), 
								item.getItemAttributes().getPublisher(), 
								StringUtil.parseDateFormat(item.getItemAttributes().getPublicationDate()));
						books.add(book);
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		return books;

	}

	public List<Item> searchItemsByKeywords(Map<String, String> param) {
		List<Item> results = new ArrayList<Item>();
		try {
			AWSECommerceServicePortType service = getWebService();
			
			ItemSearch submit = createItemSearchParameter(param);
			ItemSearchResponse response = service.itemSearch(submit);
			if (response != null) {
				if (response.getItems() != null	&& response.getItems().length > 0) {
					for (Items items :response.getItems()) {
						if (items != null) {
							//System.out.println("TotalPages: " + items.getTotalPages());
							//System.out.println("TotalResults: " + items.getTotalResults());
							setTotalPages((items.getTotalPages()!=null ? items.getTotalPages().intValue() : 0));
							setTotalResults((items.getTotalResults()!=null ? items.getTotalResults().intValue() : 0));
							//Items items = response.getItems()[0];
							if (items.getItem() != null) {
								System.out.println("result size: " + items.getItem().length);
								for (int i = 0; i < items.getItem().length; i++) {
									Item item = items.getItem()[i];
									/***
									 *  Refer: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/CHAP_response_elements.html
									 */
									results.add(item);
								}
							}
						}
					}
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}

		return results;

	}
	
	public Item searchItemsDetail(String param) {

		// TODO Display Book Title on the White Area Because some time the title of the book too long
		// TODO Display Book Description in Detail Page
		
		List<Item> results = new ArrayList<Item>();
		Item retObj = null;
		try {
			AWSECommerceServicePortType service = getWebService();

			ItemLookup lookup = createItemSearchParameterForDetail(param);

			ItemLookupResponse lookupResponse = service.itemLookup(lookup);
			
			for (Items items : lookupResponse.getItems()) {
				if (items.getItem() != null && items.getItem().length > 0) {
					Item result = items.getItem()[0];
					retObj = result;
				} else {
					//System.out.println("No Items Returned????????");
				}
			}

		} catch (RemoteException e) {
			e.printStackTrace();
		}

		return retObj;

	}
	
	public ItemLookup createItemSearchParameterForDetail(String param) {

		ItemLookup lookup = new ItemLookup();
		lookup.setAWSAccessKeyId(AWS_ACCESS_KEY_ID);
		lookup.setAssociateTag(AWS_ASSOCIATE_TAG);

		/***
		 *  Reference: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/USSearchIndexParamForItemsearch.html#USSearchIndexParamForItemsearch_books
		 */
		
		
		ItemLookupRequest lookupRequest = new ItemLookupRequest();
		lookupRequest.setIdType(ItemLookupRequestIdType.ASIN);  
		lookupRequest.setItemId(new String[]{param});
		lookupRequest.setResponseGroup(new String[] { "ItemAttributes" });
		  
		lookup.setShared(lookupRequest);
		  
		
		return lookup;
	}
	
	public ItemSearch createItemSearchParameter(Map<String, String> param) {

		ItemSearch submit = new ItemSearch();
		//submit.setAWSAccessKeyId(AWS_ACCESS_KEY_ID);
		submit.setAssociateTag(AWS_ASSOCIATE_TAG);

		/***
		 *  Reference: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/USSearchIndexParamForItemsearch.html#USSearchIndexParamForItemsearch_books
		 */
		
		ItemSearchRequest shared = new ItemSearchRequest();
		if (param.containsKey("ITEMPAGE")) {
			System.out.println("ITEMPAGE=" + param.get("ITEMPAGE"));
			shared.setItemPage(new PositiveInteger(param.get("ITEMPAGE")));
		}
		//shared.setSort("relevancerank");
		shared.setSearchIndex("Books");
		if (param.containsKey("TITLE")) {
			System.out.println("TITLE=" + param.get("TITLE"));
			shared.setTitle(param.get("TITLE"));
		}
		if (param.containsKey("AUTHOR")) {
			//String author = StringUtil.encodeURI(param.get("AUTHOR"));
			String author = StringUtil.formatCriteria(param.get("AUTHOR"));
			System.out.println("AUTHOR=" + author);
			//shared.setAuthor(author);
			shared.setPower("author-exact:'" + author+"'");
		}
		if (param.containsKey("KEYWORDS")) {
			System.out.println("KEYWORDS=" + param.get("KEYWORDS"));
			shared.setKeywords(param.get("KEYWORDS"));
		}
		shared.setResponseGroup(new String[] { "Images", "ItemAttributes" });
		submit.setShared(shared);
		/*
		ItemSearchRequest[] requests = new ItemSearchRequest[10];
		for (int i = 0; i < 10 ; i++) {
			ItemSearchRequest request = new ItemSearchRequest();
			request.setItemPage(new PositiveInteger(String.valueOf(i + 1)));
			requests[i] = request;
		}
			
		submit.setRequest(requests);
		*/
		return submit;
	}

}
